clear;
clc;
P10 = 0.1;
P01 = 0.1;	%����ָ��
N = 1000;
N0 = P01/(1-P10); %����
N1 = (1-P01) /P10; %����
s = zeros ( [1,N]) ; %�źŲ���
S = zeros ( [1,N]) ; %�źŽ��� 
check = zeros ( [1,N]); %�ź��ж� 
time = 0; %������
t = 0;

for i = 1:N     %�������1000�������ֵ����
    if (rand () ) < 0.5
    s (i) = 1;
    end
end


while(ismember(0,check)) %һ�����м��
% while(time < 100) %100�μ���ض�
% batch_size=50;    %ȡ����50��
% while(time<500)
%     if (time==(500-batch_size))
%         S = zeros ( [1,N]) ;
%     end
    time =time +1;
    SNR=3; %����ȣ���λdb
    x = noi_add(s,SNR);   %�趨�����ӵľ����ض�����ȵ�����
    for i = 1:N
        if(x(i) > log(N1)+0.5)
        S(i) = 1;
        check(i) = 1;
        elseif(x(i) < log(N0)+0.5)
        S(i) = 0;
        check(i) = 1;
        end
    end
end


for i = 1:N
    if(S (i) == s (i))
    t = t+1;
    end
end
sprintf('�����Ϊ%sdB������',num2str(SNR))
sprintf('׼ȷ��Ϊ%s%%',num2str(t/N*100))
sprintf('ƽ��ѭ��%s',num2str(time))

% function[Y,SNR] = noi(N,X) 
%     y=randn(1,N);
%     y=y/std(y);
%     y=y-mean(y);
%     Y=y+X;
%     signal_power = 1/length(X)*sum(X.*X);
%     noise_power= 1/length(y)*sum(y.*y);
%     SNR=10*log10(signal_power/noise_power);
% end

function Y =noi_add(X,SNR)
noi = randn(size(X));
noi = noi - mean(noi);
signal_power = 1/length(X)*sum(X.*X); 
variance = signal_power/(10^(-SNR/10)); 
noi=sqrt(variance)/std(noi)*noi;
Y = X + noi;
end
 